package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.RadeFiducialAdd;
import com.xmy.cultivate.entity.RadeFiducialSet;
import com.xmy.cultivate.entity.Subjects;
import com.xmy.cultivate.service.IRadeFiducialAddService;
import com.xmy.cultivate.service.IRadeFiducialSetService;
import com.xmy.cultivate.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.BeanUtils; // 用于属性复制


import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 率的基准值(手动添加) 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-05-13
 */
@RestController
@RequestMapping("/api/radeFiducialAdd")
public class RadeFiducialAddController extends BaseController {
    @Autowired
    IRadeFiducialAddService iRadeFiducialAddService;

    @Autowired
    IRadeFiducialSetService iRadeFiducialSetService;

    @Autowired
    IdWorker idWorker;

    @GetMapping("")
    public Result findAll(@RequestParam(value = "pageNum", defaultValue = "-1", required = false) Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "-1", required = false) Integer pageSize,
                          @RequestParam(value = "export", defaultValue = "0", required = false) Integer export,// 是否导出，0否1是
                          @RequestParam(value = "yearPart", required = false) String yearPart,// 年份
                          @RequestParam(value = "quarterNum", required = false) String quarterNum,// 学期
                          @RequestParam(value = "fiducialSetId", required = false) String fiducialSetId,// 项目id
                          @RequestParam(value = "yearClassId", required = false) String yearClassId,
                          @RequestParam(value = "subjectsId", required = false) String subjectsId,
                          @RequestParam(value = "isDescOrAsc", required = false) String isDescOrAsc,// 1正序，2倒序
                          @RequestParam(value = "isFieldToSc", required = false) String isFieldToSc// 要排序的字段
    ) throws IOException {

        IPage<RadeFiducialAdd> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper<RadeFiducialAdd> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(fiducialSetId), "fiducial_set_id", fiducialSetId);
        wrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        wrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        wrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        wrapper.inSql(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        wrapper.inSql("fiducial_set_id", "SELECT id FROM rade_fiducial_set WHERE `status` = 1");
        if (StringUtils.isNotBlank(isDescOrAsc)) {
            if ("1".equals(isDescOrAsc)) {
                wrapper.orderByAsc("rade_num");
            } else if ("2".equals(isDescOrAsc)) {
                wrapper.orderByDesc("rade_num");
            }
        } else {
            wrapper.orderByDesc("id");
        }

        iRadeFiducialAddService.page(iPage, wrapper);

        if (export == 1) {
            String freezingColumns = "A1:D1";
            CellRangeAddress cellRangeAddress = CellRangeAddress.valueOf(freezingColumns);

            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");
            sheet.createFreezePane(0, 1);
            sheet.setAutoFilter(cellRangeAddress);

            Row headerRow = sheet.createRow(0);
            headerRow.setHeightInPoints(30);

            CellStyle headerCellStyle = ExcelUtils.headCommonCellStyle(workbook);

            CellStyle cellStyle = ExcelUtils.bodyCommonCellStyle(workbook, null);

            List<String> headList = new ArrayList<>();
            headList.add("年份");
            headList.add("学期");
            headList.add("项目");
            headList.add("基准值");

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
                sheet.setColumnWidth(i, 25 * 256);
            }

            int rowIndex = 1;

            for (RadeFiducialAdd radeFiducialAdd : iPage.getRecords()) {
                Row row = sheet.createRow(rowIndex);

                Cell cell0 = row.createCell(0);
                cell0.setCellValue(radeFiducialAdd.getYearPart());
                sheet.setColumnWidth(0, 15 * 256);
                cell0.setCellStyle(cellStyle);

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(CommonUtil.getQuarterNameForId(radeFiducialAdd.getQuarterNum()));
                sheet.setColumnWidth(1, 15 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(radeFiducialAdd.getProjectsName());
                sheet.setColumnWidth(2, 30 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(3);
                cell3.setCellValue((radeFiducialAdd.getRadeNum() + "%"));
                sheet.setColumnWidth(3, 15 * 256);
                cell3.setCellStyle(cellStyle);

                rowIndex++;
            }

            String fileName = "基准值" + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置为excel格式
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新输出流
            outputStream.flush();

            //关闭输出流
            outputStream.close();
        }

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));

    }

    @PostMapping()
    public Result save(@RequestBody RadeFiducialAdd radeFiducialAdd) {
        RadeFiducialSet radeFiducialSet = iRadeFiducialSetService.getById(radeFiducialAdd.getFiducialSetId());

        if (radeFiducialSet == null) {
            return new Result(Code.ERROR, "", "需要先设置统计基准值的率");
        }

        List<Long> subjectsIdList = new ArrayList<>();
        List<String> yearClassIdList = new ArrayList<>();

        if (radeFiducialAdd.getSubjectsId() == null) {
            if (radeFiducialSet.getSubjectsId() == 0) {
                for (long i = 0; i < 4; i++) {
                    subjectsIdList.add(i);
                }
            } else {
                subjectsIdList.add(radeFiducialSet.getSubjectsId());
            }
        } else {
            subjectsIdList.add(radeFiducialAdd.getSubjectsId());
        }

        if (radeFiducialAdd.getYearClassId() == null) {
            yearClassIdList.add("");
            for (int i = 0; i < 13; i++) {
                yearClassIdList.add(String.valueOf(i));
            }
        } else {
            yearClassIdList.add(String.valueOf(radeFiducialAdd.getYearClassId()));
        }

        StringBuilder sb = new StringBuilder();
        sb.append(radeFiducialSet.getProjectsName());
        Integer isRepetition = 0;
        for (String yearClassId : yearClassIdList) {
            for (Long subjectsId : subjectsIdList) {

                if (StringUtils.isNotBlank(yearClassId)) {
                    int yearClassInt = Integer.parseInt(yearClassId);
                    if (yearClassInt < 8 && subjectsId == 3L) {
                        continue;
                    }
                }

                RadeFiducialAdd currentAdd = new RadeFiducialAdd();
                BeanUtils.copyProperties(radeFiducialAdd, currentAdd);

                QueryWrapper<RadeFiducialAdd> wrapper = new QueryWrapper<>();
                wrapper.eq("fiducial_set_id", currentAdd.getFiducialSetId());
                wrapper.eq("year_part", currentAdd.getYearPart());
                wrapper.eq("quarter_num", currentAdd.getQuarterNum());
                wrapper.eq("subjects_id", subjectsId);
                if (StringUtils.isNotBlank(yearClassId)) {
                    wrapper.eq("year_class_id", yearClassId);
                } else {
                    wrapper.isNull("year_class_id");
                }
                if (currentAdd.getId() != null) {
                    wrapper.ne("id", currentAdd.getId());
                }
                wrapper.last(" limit 1");
                RadeFiducialAdd fiducialAdd = iRadeFiducialAddService.getOne(wrapper);

                if (fiducialAdd != null) {
                    isRepetition = 1;
                    if (StringUtils.isNotBlank(yearClassId)) {
                        sb.append(CommonUtil.getYearClassNameForId(Integer.valueOf(yearClassId)));
                    } else {
                        sb.append("全部年级");
                    }
                    if (subjectsId != 0) {
                        sb.append(CommonUtil.getSubjectsNameForId(Math.toIntExact(subjectsId)));
                    } else {
                        sb.append("全部科目");
                    }
                    sb.append("、");
                }
            }
        }

        if (isRepetition == 1) {
            sb.deleteCharAt(sb.length() - 1);
            sb.append("，已经设置过基准值，请不要重复设置");
            return new Result(Code.ERROR, "", sb.toString());
        }

        for (String yearClassId : yearClassIdList) {
            for (Long subjectsId : subjectsIdList) {

                if (StringUtils.isNotBlank(yearClassId)) {
                    int yearClassInt = Integer.parseInt(yearClassId);
                    if (yearClassInt < 8 && subjectsId == 3L) {
                        continue;
                    }
                }

                RadeFiducialAdd currentAdd = new RadeFiducialAdd();
                BeanUtils.copyProperties(radeFiducialAdd, currentAdd);

                if (currentAdd.getId() == null) {
                    currentAdd.setId(idWorker.nextId());
                }

                currentAdd.setSubjectsId(subjectsId);
                if (StringUtils.isNotBlank(yearClassId)) {
                    currentAdd.setYearClassId(Integer.valueOf(yearClassId));
                } else {
                    currentAdd.setYearClassId(null);
                }
                currentAdd.setLessonType(radeFiducialSet.getLessonType());
                currentAdd.setProjectsId(radeFiducialSet.getProjectsId());
                currentAdd.setProjectsName(radeFiducialSet.getProjectsName());

                iRadeFiducialAddService.saveOrUpdate(currentAdd);
            }
        }

        return new Result(Code.OK, "", Code.SAVE_OK_MSG);
    }

    @DeleteMapping("")
    public Result delAccount(@RequestParam(value = "idStr") String idStr) {
        String[] ids = idStr.split(",");
        for (String id : ids) {
            RadeFiducialAdd radeFiducialAdd = iRadeFiducialAddService.getById(id);
            if (Objects.isNull(radeFiducialAdd)) {
                return new Result(Code.EXP_ERROR, null, "该数据不存在");
            }

            iRadeFiducialAddService.removeById(id);
        }

        return new Result(Code.OK, "", Code.DELETE_OK_MSG);
    }

}
